package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.example.common.R;
import org.example.entity.Cart;
import org.example.entity.CartDTO;
import org.example.entity.Dish;
import org.example.service.CartService;
import org.example.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * TODO 类描述
 *
 * @author shaoxuan.
 * @date 2024/2/21 23:11
 */
@RestController
@Api(tags = "购物车管理")
@RequestMapping("/cart")
@Slf4j
public class CartController {

    @Autowired
    private CartService service;
    @Autowired
    private DishService dishService;

    @PostMapping("/add")
    @ApiOperation(value = "新增购物车菜品")
    public R<Cart> Add(@RequestBody Cart cart) {
        Dish one = dishService.getOne(new LambdaQueryWrapper<Dish>().eq(Dish::getId, cart.getDishid()));
        if (one == null) {
            return R.error("菜品不存在");
        } else {
            service.save(cart);
            return R.success(cart).setMsg("添加成功");
        }
    }


    @GetMapping("/get/{userId}")
    @ApiOperation(value = "获取当前用户购物车菜品")
    public R<List<CartDTO>> get(@PathVariable("userId") String userId) {
        List<Cart> list = service.list(new LambdaQueryWrapper<Cart>().eq(Cart::getUserid, userId));
        List<CartDTO> res = new LinkedList();
        for (int i = 0; i < list.size(); i++) {
            CartDTO dto = new CartDTO();
            Cart cart = list.get(i);
            BeanUtils.copyProperties(cart, dto);
            Dish byId = dishService.getById(cart.getDishid());
            BeanUtils.copyProperties(byId, dto);
            res.add(dto);

        }
        return R.success(res);

    }

    @DeleteMapping("/del")
    @ApiOperation(value = "删除购物车菜品")
    public R deleteById( @RequestBody Cart cart){
        LambdaQueryWrapper<Cart> eq = new LambdaQueryWrapper<Cart>().eq(Cart::getDishid, cart.getDishid());
        service.remove(eq);
        return R.success(null).setMsg("删除成功");
    }

    @PutMapping("/update")
    @ApiOperation(value = "修改购物车菜品")
    public R update( @RequestBody Cart cart){
        service.updateById(cart);
        return R.success(cart).setMsg("修改成功");
    }


    @DeleteMapping("/removeall/{userId}")
    @ApiOperation(value = "清空购物车菜品")
    public R removeall(@PathVariable("userId") String userId){
        boolean remove = service.remove(new LambdaQueryWrapper<Cart>().eq(Cart::getUserid, userId));
        return R.success(null).setMsg("清空成功");
    }

}
